import { AppCTX } from "../../types/koaExtend";
import { createBrandApiMWRouter } from "../../middleware/brand-api/brandAdminChecker";
import pageMW from "../../middleware/pager";
import {
  createProduct,
  updateProduct,
  removeProduct,
  getProduct,
  listNormalProductsByBrandID,
} from "../../service/productService";
import { Brand } from "../../service/declareTypes";
// import {
//   getBrand,
//   getBrandWebTokenSafely,
// } from "../../service/brandService";
import {
  getRemotePrdTypeIdSafely,
  getRemotePropertyGroupIdSafely,
  addWebposPrd,
  editWebposPrd,
} from "../../proxy/webPosProxy";
import { isUndefined, _pick } from "mmb";

const router = createBrandApiMWRouter();

// 获取品牌商品列表
router.get(
  "brand-products",
  "/brd/:brandId/products",
  pageMW,
  async (ctx: AppCTX, next) => {
    const { brandId } = ctx.params;
    let { productGroupId, keyword } = ctx.query;
    const { userId, limit, offset, ts } = ctx;

    const { total, items } = await listNormalProductsByBrandID(
      { brandId, productGroupId, keyword },
      {
        limit,
        offset,
        ts,
      }
    );

    ctx.body = {
      total,
      rows: items.map((it) => ({
        ..._pick(
          it,
          "productId",
          "name",
          "pics",
          "hasSpecs",
          "priceMin",
          "priceMax",
          "productSpecs"
        ),
        productSpecs: it.productSpecs.map((it2) => ({
          ..._pick(it2, "productSpecId", "name", "price"),
        })),
      })),
    };
  }
);

// 获取品牌商品详情
router.get("/brd/:brandId/product/:productId", async (ctx: AppCTX, next) => {
  const { brandId, productId } = ctx.params;
  const { userId } = ctx;

  const product = await getProduct(productId);

  ctx.body = {
    ..._pick(
      product,
      "productId",
      "name",
      "pics",
      "intro",
      "introPics",
      "hasSpecs",
      "priceMin",
      "priceMax",
      "productGroupId",
      "productAttributeDefs",
      "productSpecs",
      "remotePK"
    ),
  };
});

// // 确保商品分类安全
// router.post(
//   "/brd/:brandId/product/ensurePrdType",
//   async (ctx: AppCTX, next) => {
//     const { brandId } = ctx.params;
//     const { userId } = ctx;

//     const brand: Brand = await getBrand(brandId);

//     const webposToken = await getBrandWebTokenSafely(brandId);

//     const remotePrdTypeId = await getRemotePrdTypeIdSafely(
//       webposToken,
//       brand.name
//     );

//     console.log("remotePrdTypeId=>", remotePrdTypeId);
//     ctx.body = {
//       ..._pick(brand, "name"),
//       remotePrdTypeId,
//     };
//   }
// );

// 确保商品属性组安全
// router.post(
//   "/brd/:brandId/product/ensurePropertyGroups",
//   async (ctx: AppCTX, next) => {
//     const { brandId } = ctx.params;
//     const { userId } = ctx;
//     let { productAttributeDefs } = ctx.request.body;

//     const webposToken = await getBrandWebTokenSafely(brandId);
//     productAttributeDefs = await getRemotePropertyGroupIdSafely(
//       webposToken,
//       productAttributeDefs
//     );

//     ctx.body = {
//       rows: productAttributeDefs,
//     };
//   }
// );

// 新增品牌商品
router.post("/brd/:brandId/product", async (ctx: AppCTX, next) => {
  const { brandId } = ctx.params;
  const { userId } = ctx;
  const {
    name,
    price, // 不传的话是有规格 productSpecs.length必须>0
    pics,
    intro,
    introPics,
    productGroupId,
  } = ctx.request.body;
  let { productAttributeDefs, productSpecs } = ctx.request.body;

  if (isUndefined(productAttributeDefs)) {
    productAttributeDefs = [];
  }
  if (isUndefined(productSpecs)) {
    ctx.throw(400, "必须传入规格");
  }

  // if (productSpecs.length === 0 && isUndefined(price)) {
  //   ctx.throw(400, "无规格商品必须传商品价格");
  // }

  // const webposToken = await getBrandWebTokenSafely(brandId);

  // const brand: Brand = await getBrand(brandId);
  // const remotePrdTypeId = await getRemotePrdTypeIdSafely(
  //   webposToken,
  //   brand.name
  // );
  // if (productAttributeDefs.length > 0) {
  //   productAttributeDefs = await getRemotePropertyGroupIdSafely(
  //     webposToken,
  //     productAttributeDefs
  //   );
  // }

  // const p = await addWebposPrd(
  //   webposToken,
  //   brandId,
  //   productAttributeDefs
  // )({
  //   name,
  //   price,
  //   pics,
  //   intro,
  //   introPics,
  //   productGroupId,
  //   productSpecs,
  //   remotePrdTypeId,
  // });

  const product = await createProduct({
    brandId,
    name,
    price,
    pics,
    intro,
    introPics,
    productGroupId,
    productAttributeDefs,
    productSpecs,
  });
  ctx.body = {
    ..._pick(
      product,
      "productId",
      "name",
      "pics",
      "intro",
      "introPics",
      "hasSpecs",
      "priceMin",
      "priceMax",
      "productGroupId",
      "productAttributeDefs",
      "productSpecs",
      "remotePK"
    ),
  };
});

// 移除品牌商品
router.delete("/brd/:brandId/product/:productId", async (ctx: AppCTX, next) => {
  const { brandId, productId } = ctx.params;
  const { userId } = ctx;
  // 仅本地删除

  const product = await removeProduct({ productId });

  ctx.body = {
    ..._pick(
      product,
      "productId",
      "name",
      "pics",
      "intro",
      "introPics",
      "hasSpecs",
      "priceMin",
      "priceMax",
      "productGroupId",
      "productAttributeDefs",
      "productSpecs",
      "remotePK"
    ),
  };
});

// 更新品牌商品
router.put("/brd/:brandId/product/:productId", async (ctx: AppCTX, next) => {
  const { brandId, productId } = ctx.params;
  const { userId } = ctx;
  const {
    name,
    price,
    pics,
    intro,
    introPics,
    productGroupId,
    remotePK,
  } = ctx.request.body;
  let { productSpecs, productAttributeDefs } = ctx.request.body;

  if (isUndefined(productAttributeDefs)) {
    productAttributeDefs = [];
  }
  if (isUndefined(productSpecs)) {
    ctx.throw(400, "必须传入规格");
  }

  // if (productSpecs.length === 0 && isUndefined(price)) {
  //   ctx.throw(400, "无规格商品必须传商品价格");
  // }

  // const webposToken = await getBrandWebTokenSafely(brandId);
  // const brand: Brand = await getBrand(brandId);
  // const remotePrdTypeId = await getRemotePrdTypeIdSafely(
  //   webposToken,
  //   brand.name
  // );
  // if (productAttributeDefs.length > 0) {
  //   productAttributeDefs = await getRemotePropertyGroupIdSafely(
  //     webposToken,
  //     productAttributeDefs
  //   );
  // }

  // const p = await editWebposPrd(
  //   webposToken,
  //   productId,
  //   productAttributeDefs
  // )({
  //   remotePK,
  //   name,
  //   price,
  //   pics,
  //   intro,
  //   introPics,
  //   productGroupId,
  //   productSpecs,
  //   remotePrdTypeId,
  // });

  const product = await updateProduct({
    productId,
    brandId,
    name,
    price,
    pics,
    intro,
    introPics,
    productGroupId,
    productAttributeDefs,
    productSpecs,
  });

  //2 根据sync_id发送同步消息给商品系统
  ctx.body = {
    ..._pick(
      product,
      "productId",
      "name",
      "pics",
      "intro",
      "introPics",
      "hasSpecs",
      "priceMin",
      "priceMax",
      "productGroupId",
      "productAttributeDefs",
      "productSpecs",
      "remotePK"
    ),
  };
});

/* 导入相关的功能暂时不实现
// 获取未导入的商品中心商品列表
router.get("/brd/:brandId/unimportedPCProducts", async (ctx: AppCTX, next) => {
  const { brandId } = ctx.params;
  const { userId } = ctx;

  ctx.body = {
    brandId,
    userId,
    products: [
      {
        syncId: (103).toString(),
        name: "商品名称",
        pics: ["pic1", "pic2"],
        priceMin: 10,
        priceMax: 10,
      },
    ],
  };
});

// 导入商品中心商品
router.post("/brd/:brandId/product/import", async (ctx: AppCTX, next) => {
  const { brandId } = ctx.params;
  const { syncIds } = ctx.request.body;
  const { userId } = ctx;

  //2 根据sync_id发送异步消息给商品分组系统
  ctx.body = {
    userId, //操作人
    syncIds,
    brandId,
  };
});
*/
export default router;
